package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.LogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItemParser;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;
import lombok.extern.slf4j.Slf4j;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Optional;

@Slf4j
public class LogItemParserHrjImpl implements LogItemParser {

    @Override

    public Optional<LogItem> parse(NginxLogItem nginxLogItem) {
        //TODO 去除无效访问数据
        String request = nginxLogItem.getRequest();
        if (request == null || request.length() < 3 || !request.contains("HTTP")) {
            return Optional.empty();
        } else {
            String method = request.substring(0, 3);

            if (!"GET".equals(method)) {
                return Optional.empty();
            }

            String path;
            int index1 = request.indexOf(" ");
            int index2 = request.indexOf("H");
            String URL = request.substring(index1+2, index2-1);

            if (URL.contains("?")) {
                path = URL.substring(0, URL.indexOf("?"));
            } else {
                path = URL;
            }

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String dateStr = "2023-07-31 15:11:30";
            LocalDateTime dateTime = LocalDateTime.parse(dateStr, fmt);

            LogItem logItem = new LogItem(nginxLogItem.getIp(), dateTime, method, path, new HashMap<String, String>(), "HTTP", 200, 200L, " ", " ");

            return Optional.of(logItem);
        }

    }
}
